package com.line.myprojectservice.controller;

import cn.hutool.jwt.JWT;
import com.line.myprojectservice.po.User;
import com.line.myprojectservice.service.UserService;
import com.line.myprojectservice.utils.ResponseUtil;
import org.springframework.web.bind.annotation.*;

import static com.line.myprojectservice.constant.Constants.JWT_SECRET;


@RestController
@RequestMapping("/user")
public class UserController {

    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    @PostMapping("/login")
    public ResponseUtil login(@RequestBody User user) {
        User user1 = userService.queryUserById(user.getUserId());

        if (user1 != null && user1.getUserPassword().equals(user.getUserPassword())) {
            user1.setUserPassword(null);
            String token = JWT.create()
                    .setPayload("user", user1)
                    .setKey(JWT_SECRET).sign();
            return ResponseUtil.success("登录成功", token);
        } else {
            return ResponseUtil.error(-1, "用户名或密码错误");
        }
    }

    @GetMapping("/queryUserInfoById/{id}")
    public ResponseUtil queryUserInfoById(@PathVariable String id) {
        return ResponseUtil.success(userService.queryUserById(id));
    }

    @PostMapping("/register")
    public ResponseUtil register(@RequestBody User user) {
        User res = userService.queryUserById(user.getUserId());
        if (res != null) {
            return ResponseUtil.error(-1, "用户名重复");
        } else {
            userService.addUser(user);
            String token = JWT.create()
                    .setPayload("user", user)
                    .setKey(JWT_SECRET).sign();
            return ResponseUtil.success("注册成功", token);
        }
    }

    @PutMapping("")
    public ResponseUtil modifyUserInfo(@RequestBody User user) {
        userService.modifyUserInfo(user);
        return ResponseUtil.success("更新成功");
    }


    @GetMapping("/{id}")
    public ResponseUtil getById(@PathVariable String id) {
        return ResponseUtil.success(userService.queryUserById(id));
    }


}


